package com.unionftech.content_login.model

import com.google.gson.Gson
import com.unionftech.baselibrary.base.BaseApplication
import com.unionftech.common.base.mvp.impl.IBaseCallBack
import com.unionftech.common.bean.ResponseResult
import com.unionftech.common.network.SimpleNetWork
import com.unionftech.common.utils.Utils
import com.unionftech.content_login.bean.LoginTokenInfo
import com.unionftech.content_login.bean.request.RegisterRequest
import com.unionftech.content_login.contract.RegisterContract
import com.unionftech.content_login.manager.ApiManager
import com.unionftech.content_login.service.LoginConstants
import com.unionftech.content_login.util.TokenManager
import okhttp3.RequestBody.Companion.toRequestBody

class RegisterModel : BaseParentModel(), RegisterContract.IRegisterModel {

    override fun unionfRegister(
        registerRequest: RegisterRequest,
        callBack: IBaseCallBack<ResponseResult<LoginTokenInfo>>?
    ) {
        execute {
            val result = request {
                val uuid = Utils.generateUniqueId(BaseApplication.appContext)
                val model = Utils.getPrettyDeviceName()
                val version = "V" + Utils.getVersionName(BaseApplication.appContext)
                val content = Gson().toJson(registerRequest, RegisterRequest::class.java)
                val body = content.toRequestBody(SimpleNetWork.JSON)
                ApiManager.getInstance().apiRegister().unionfRegister(uuid, model, version, body)
            }
            if (result.code == ResponseResult.SUCCESS_CODE
                || result.code == LoginConstants.Code.REGISTER_LOGIN_SUCCESS
            ) {
                //存储登录token
                result.data?.let {
                    TokenManager.getInstance().saveToken(it)
                }
            }
            result.data = null
            callBack?.onResponse(result)
        }
    }
}